//
//  SampleNetWorks.swift
//  SampleNetWorks
//
//  Created by apple on 15/3/4.
//  Copyright (c) 2015年 Ai. All rights reserved.
//

import Foundation


public enum HTTPMethod:String{
    case POST = "POST"
    case GET = "GET"
}

public class SampleNeworks{
    
    static var cachePath = "MyImgCacheFolder"
 /// 缓存图片路径懒加载
    lazy var cacheImageUrl :String? = {
        // 1.创建缓存路径
    var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
        path = path.stringByAppendingString(cachePath)
        println(path)
        // 2.检查该目录是否存在
        // 3.如果存在的是文件，不是目录，删除
        // 4.如果该目录不存在，创建
        return nil
    }()
    
    
    
    
    ///  session懒加载
    lazy var session : NSURLSession? = {
        
        return NSURLSession.sharedSession()
        }()
    
    public typealias completions = (result:AnyObject?,error:NSError?) ->()
    
    ///  请求Json
    ///
    ///  :param: method     请求方法
    ///  :param: urlString  urlString
    ///  :param: params     可选字典参数
    ///  :param: completion 回调---闭包
    public func requestJson(method:HTTPMethod,urlString:String,params:[String:String]?,completion:completions){
        
        if let req = request(method, urlString: urlString, params: params){
    
            session!.dataTaskWithRequest(req, completionHandler: { (data, _, error) -> Void in
                // 如果有错误
                if error != nil {
                    completion(result: nil, error: error)
                    return
                }else{
                    // 如果没有错误
                    let json: AnyObject?  = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
                    
                    // 反序列化失败
                    if json == nil{
                        let error = NSError(domain: "NB----Error", code: 0, userInfo: ["error" : "序列化失败"])
                        completion(result: nil, error: error)
                    }else{
                        // 序列化成功
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            completion(result: json, error: nil)
                        })
                    }
                }
            }).resume()
        } else {
            let error = NSError(domain: "NB----Error", code: -1, userInfo: ["error" : "请求失败"])
            
            completion(result: nil, error: error)
        }
    }
    
    ///  网络请求
    ///
    ///  :param: method    请求方法
    ///  :param: urlString 网址
    ///  :param: params    可选字典
    func request(method:HTTPMethod,urlString:String,params:[String:String]?) -> NSURLRequest?{
        
        var req : NSMutableURLRequest?
        
        //urlString.isEmpty
        if urlString.isEmpty{
            return nil
        }
        // 取出拼接好的参数
        var str = urlString
        if method == HTTPMethod.GET{
            let query = queryString(params)
            // GET 请求
            if query != nil {
                str += "?" + query!
            }
            req = NSMutableURLRequest(URL: NSURL(string: str)!)
            
        }else{
            // POST请求
            if let query = queryString(params) {

                req = NSMutableURLRequest(URL: NSURL(string: str)!)
                req!.HTTPMethod = method.rawValue
                req!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            }
        }
        return req
    }
    
    
    ///  拼接字符串
    ///
    ///  :param: params 可选字典
    public func queryString(params:[String:String]?)->String?{
        if params == nil{
            return nil
        }
        var array = [String]()
        for(k,var v) in params!{
           // v = v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            let str = k + "=" + v
            array .append(str)
        }
        // 最后返回 "name = zhangsan & age = 34"
        return join("&", array)
        
    }
    
    // 构造初始化函数
    public init(){
        
    }
    
    
}